using System.Text;
using DealerPlatform.Common.EventBusHelper;
using DealerPlatform.Common.RedisModule;
using DealerPlatform.Common.TokenModule.Models;
using DealerPlatform.Core.Core;
using DealerPlatform.Extensions;
using DealerPlatform.Service;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(c => c.AddPolicy("any", p => p
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowAnyOrigin()));

var token = builder.Configuration.GetSection("Jwt").Get<JwtTokenModel>();

#region Jwt验证

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(
        opt =>
        {
            // 是否是https，默认为true，开发环境下设置为false
            opt.RequireHttpsMetadata = false;
            opt.SaveToken = true;
            opt.TokenValidationParameters = new()
            {
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Security)),
                ValidIssuer = token.Issuer,
                ValidAudience = token.Audience
            };
            opt.Events = new JwtBearerEvents
            {
                OnChallenge = context =>
                {
                    // 此处终止代码
                    context.HandleResponse();
                    var res = "{\"code\":401,\"err\":\"无权限\"}";
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    context.Response.WriteAsync(res);
                    return Task.FromResult(0);
                }
            };
        });

#endregion

builder.Services.AddDbContext<DealerPlatformContext>(opt =>
{
    opt.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
});

// builder.Services.AddScoped<ICustomerService, CustomerService>();
// builder.Services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
builder.Services.RepositoryRegister();
builder.Services.ServiceRegister();
builder.Services.AddAutoMapper(typeof(DealerPlatformAutoMapperProfile));

builder.Services.AddScoped(typeof(LocalEventBus<>));
builder.Services.AddSingleton<RedisCore>();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = $"格式：Bearer{token}",
        Name = "Authorization", // 默认的参数名
        In = ParameterLocation.Header, // 放于请求头中
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    // 添加安全要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] { }
        }
    });
});

var app = builder.Build();

app.UseCors("any");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseHttpsRedirection();
app.MapControllers();
app.UseAuthorization();

app.Run();